package com.atguigu.gulimall.cart.controller;

import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.CartItemVo;
import com.atguigu.gulimall.cart.vo.CartVo;
import org.bouncycastle.math.raw.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;

    @GetMapping("/{memberId}/currentCartItems")
    @ResponseBody
    public List<CartItemVo> currentMemberCartitems(@PathVariable("memberId")Long memverId){
        return cartService.currentMemberCartitems(memverId);
    }

    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId")Long skuId){
        cartService.deleteItem(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId,@RequestParam("count") Integer count){
        cartService.countItem(skuId,count);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId,@RequestParam("checked") Boolean checked){
        cartService.checkItem(skuId,checked);

        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @GetMapping("/cart.html")
    public String cart(Model model) throws ExecutionException, InterruptedException {
        CartVo cartVo = cartService.getCartAndItems();
        model.addAttribute("cart",cartVo);
        return "cartList";
    }

    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("num") Integer num, @RequestParam("skuId") Long skuId
            , RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {
        //加入购物车
        cartService.addToCart(skuId, num);
        //请求转发的url地址不变，如果添加后再次刷新页面，就会导致重复提交，因此可以重定向解决重复提交的问题
        redirectAttributes.addAttribute("skuId", skuId);//将改键值对作为参数拼接到到url地址后面
        return "redirect:http://cart.gulimall.com/addToCartSuccess";
    }

    @GetMapping("/addToCartSuccess")
    public String addToCartSuccess(@RequestParam("skuId") Long skuId, Model model) {
        //根据skuId查询当前购物项数据
        CartItemVo cartItemVo = cartService.getCartItem(skuId);
        model.addAttribute("item", cartItemVo);
        return "success";
    }
}
